/**
 * 字典
 *
 */
import type { DictTypes } from "./types/dict";
import Taro from "@tarojs/taro";
import { request } from "@/lib/request";
/**
 * constants
 */
const actionPrefix = `Dict/`;
export const SET_DICT = actionPrefix + "SET_DICT";
export const CLEAR = actionPrefix + "CLEAR";
import { store } from "@/store";

/**
 * 查询全部字典配置
 *
 */
export const ApiGetData = (data: any) => {
  return request({
    url: "/post/dict",
    method: "POST",
    data,
  });
};

/**
 * actions
 */
/**
 * 设置字典
 * @param {}
 * @return
 */
export const setDict = (data: DictTypes["data"]) => {
  return {
    type: SET_DICT,
    data,
  };
};
/**
 * 清除
 * @param {}
 * @return
 */
export const clear = () => {
  return {
    type: CLEAR,
  };
};
/**
 * 获取字典数据
 * @param {}
 * @return
 */
export function getData({
  setServiceError,
  setServiceErrorMsg,
  callback = () => {},
}: any) {
  return (dispatch) => {
    const { dict } = store.getState();
    if (dict?.data?.length < 1) {
      const storageData: any = Taro.getStorageSync("dict");
      if (
        storageData &&
        new Date().getTime() - 1000 * storageData.cacheTime <
          storageData.exipreTime
      ) {
        dispatch(setDict(storageData.dict));
        dictUtils.set(storageData.dict);
        callback();
      } else {
        ApiGetData({})
          .then((res) => {
            if (res?.data?.list) {
              dispatch(setDict(res?.data?.list));
              Taro.setStorageSync("dict", {
                dict: res?.data?.list,
                exipreTime: new Date().getTime(),
                cacheTime: process.env.DICT_CACHE_TIME,
              });
              dictUtils.set(res?.data?.list);
            }
          })
          .catch((_e) => {
            setServiceError(true);
            setServiceErrorMsg("获取系统字典请求失败");
          })
          .finally(() => {
            callback();
          });
      }
    } else {
      callback();
    }
  };
}

/**
 * state
 */
const INITIAL_STATE: DictTypes = {
  data: [],
};
export default function user(state = INITIAL_STATE, action) {
  switch (action.type) {
    case SET_DICT:
      return {
        ...state,
        data: action.data,
      };
    case CLEAR:
      return INITIAL_STATE;
    default:
      return state;
  }
}

/**
 * 工具方法
 */
export const dictUtils = {
  /**
   * 设置
   * @param {}
   * @return
   */
  set: (data) => {
    dictUtils.data = data || [];
  },
  /**
   * 字典数据
   */
  data: [],
  /**
   * @dec 获取字典某类型的数据
   * @param {String} type 字典类型
   * */
  getType: (type) => dictUtils.data.filter((v: any) => v.categoryCode === type),
  /**
   * @dec 获取字典多类型的数据集合
   * @param {Array[String]} types 字典类型集合
   * */
  getTypes: (types) => {
    let _data = [];
    types.forEach((_type) => {
      const _i = dictUtils.getType(_type);
      if (_i) {
        _data = _data.concat(_i);
      }
    });
    return _data;
  },
  /**
   * 根据类型及code获取value
   * @param {}
   * @return
   */
  getValueFromTypeCode: ({ type, code }) => {
    const _type: any = dictUtils.getType(type);
    if (_type && _type.length) {
      const _dict = _type.find((item) => item.code == code);
      return _dict && _dict.value;
    }
    return code;
  },
  /**
   * 根据类型及code获取name
   * @param {}
   * @return
   */
  getNameFromTypeCode: ({ type, code }) => {
    const _type: any = dictUtils.getType(type);
    if (_type && _type.length) {
      const _dict = _type.find((item) => item.code == code);
      return _dict && _dict.name;
    }
    return code;
  },
  /**
   * 根据类型及name获取code
   * @param {}
   * @return
   */
  getCodeFromTypeName: ({ type, name }) => {
    const _type: any = dictUtils.getType(type);
    if (_type && _type.length) {
      const _dict = _type.find((item) => item.name === name);
      return _dict && _dict.code;
    }
    return name;
  },
};
